package com.tsx.china.mobile.ai.service.impl;

import com.tsx.china.mobile.ai.service.ChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.time.LocalDateTime;

@Service
@Slf4j
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {
    private final VectorStore vectorStore;
    private final ChatClient chatClient;

    @Override
    public Flux<String> chat(String sessionId, String question) {
        SearchRequest searchRequest = SearchRequest.builder()
                .query(question)
                .build();
        QuestionAnswerAdvisor questionAnswerAdvisor = QuestionAnswerAdvisor.builder(vectorStore)
                .searchRequest(searchRequest)
                .build();
        return chatClient.prompt(question)
                .advisors(advisorSpec -> advisorSpec
                        .param(ChatMemory.CONVERSATION_ID, sessionId)
                        .advisors(questionAnswerAdvisor))
                .system(promptSystemSpec -> promptSystemSpec
                        .param("now", LocalDateTime.now()))
                .stream()
                .content()
                .concatWith(Flux.just("[END]"));
    }
}
